﻿using System.Windows;
using Microsoft.Phone.Scheduler;
using OnlineVideos.Data;
using Common.Library;
using System.Linq;
using System.Net;
using System;
using System.Data.Linq;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using PicasaMobileInterface;
using OnlineVideos.Entities;
using System.IO;
//using PicasaMobileInterface1;


namespace WebSliceBackAgent
{
    //scheduleAgent for videomix //scheduleAgent for videomix
    public class ScheduledAgent : ScheduledTaskAgent
    {

        protected override void OnInvoke(ScheduledTask task)
        {
            try
            {
                SQLite.SQLiteAsyncConnection conn = new SQLite.SQLiteAsyncConnection(Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "OnlineMoviesDb.sqlite").ToString());
                //OnlineVideoDataContext context = new OnlineVideoDataContext(Constants.DatabaseConnectionString);
                if (conn.Table<ShareTable>().FirstOrDefaultAsync().Result != null)
                {
                    foreach (ShareTable st in conn.Table<ShareTable>().Where(i => i.NextPostTime < System.DateTime.Now).ToListAsync().Result)
                    {
                        // UploadToBlog ub = new UploadToBlog(st.ShowID, st.Description, st.ImageUrl);
                        break;
                    }
                }

                if (conn.Table<WebDailyTable>().Where(i => i.Status == "Changed").OrderByDescending(i => i.Date).FirstOrDefaultAsync().Result != null)
                {
                    SQLite.AsyncTableQuery<WebDailyTable> DTable = conn.Table<WebDailyTable>().Where(i => i.Status == "Changed").OrderByDescending(i => i.Date).Take(5);
                    foreach (WebDailyTable wt in DTable.ToListAsync().Result.Where(i => i != null))
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            CreateTileImage CI = new CreateTileImage(wt.ShowID.ToString(), this);
                        });
                    }
                }
                else
                {
                    NotifyComplete();
                }
            }
            catch (Exception ex)
            {
                NotifyComplete();
            }

        }
        public void complete()
        {
            NotifyComplete();
        }
    }
}